Conversion between int and byte[] in Java

  • 2020-05-17 05:28:39
  • OfStack

In the previous project, when communicating with Socket, the value of int type needs to be transmitted. However, it seems that outputsteam in java cannot directly transmit int type, but only byte[]. Therefore, the method of transferring int and byte[] is recorded here.


/** 
* int turn byte[] 
*/ 
public static byte[] intToBytes(int i) { 
byte[] bytes = new byte[4]; 
bytes[0] = (byte) (i & 0xff); 
bytes[1] = (byte) ((i >> 8) & 0xff); 
bytes[2] = (byte) ((i >> 16) & 0xff); 
bytes[3] = (byte) ((i >> 24) & 0xff); 
return bytes; 
}

When receiving, turn 1 again


/** 
* byte[] turn int 
*/ 
public static int bytesToInt(byte[] bytes) { 
int i; 
i = (int) ((bytes[0] & 0xff) | ((bytes[1] & 0xff) << 8) 
| ((bytes[2] & 0xff) << 16) | ((bytes[3] & 0xff) << 24)); 
return i; 
}

Related articles: